import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 游记JSON文件路径
const TRAVELS_FILE_PATH = path.join(__dirname, '../data/travels.json');

// 读取游记数据
const readTravelsData = () => {
  try {
    const data = fs.readFileSync(TRAVELS_FILE_PATH, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error('读取游记数据失败:', error);
    return [];
  }
};

// 写入游记数据
const writeTravelsData = (data) => {
  try {
    fs.writeFileSync(TRAVELS_FILE_PATH, JSON.stringify(data, null, 2), 'utf8');
    return true;
  } catch (error) {
    console.error('写入游记数据失败:', error);
    return false;
  }
};

/**
 * 获取游记列表
 * @route GET /api/travels
 * @param {number} page - 页码，默认为1
 * @param {number} limit - 每页数量，默认为10
 * @param {string} search - 搜索关键词（可选）
 * @returns {object} 包含游记列表和分页信息的对象
 */
export const getTravels = (req, res) => {
  try {
    // 获取查询参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const search = req.query.search || '';

    // 获取所有游记数据
    let travels = readTravelsData();

    // 如果有搜索关键词，进行过滤
    if (search) {
      travels = travels.filter(travel =>
        travel.title.toLowerCase().includes(search.toLowerCase()) ||
        travel.content.toLowerCase().includes(search.toLowerCase()) ||
        travel.location.toLowerCase().includes(search.toLowerCase()) ||
        travel.author.nickname.toLowerCase().includes(search.toLowerCase())
      );
    }

    // 只返回已审核通过的游记
    travels = travels.filter(travel => travel.status === 'approved' && !travel.isDeleted);

    // 计算分页
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const total = travels.length;

    // 分页结果
    const paginatedTravels = travels.slice(startIndex, endIndex);

    // 返回结果
    return res.status(200).json({
      success: true,
      count: paginatedTravels.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: page,
      data: paginatedTravels
    });
  } catch (error) {
    console.error('Error getting travels:', error);
    return res.status(500).json({
      success: false,
      error: '获取游记列表失败'
    });
  }
};

/**
 * 获取游记详情
 * @route GET /api/travels/:id
 * @param {string} id - 游记ID
 * @returns {object} 游记详情
 */
export const getTravelById = (req, res) => {
  try {
    const { id } = req.params;
    const travels = readTravelsData();

    // 查找指定ID的游记
    const travel = travels.find(t => t.id === id && t.status === 'approved' && !t.isDeleted);

    if (!travel) {
      return res.status(404).json({
        success: false,
        error: '游记不存在或已被删除'
      });
    }

    return res.status(200).json({
      success: true,
      data: travel
    });
  } catch (error) {
    console.error('Error getting travel by id:', error);
    return res.status(500).json({
      success: false,
      error: '获取游记详情失败'
    });
  }
};

/**
 * 创建新游记
 * @route POST /api/travels
 * @param {object} travel - 游记信息
 * @returns {object} 创建结果
 */
export const createTravel = (req, res) => {
  try {
    const { title, content, location, images, video, author } = req.body;

    // 验证必要字段
    if (!title || !content) {
      return res.status(400).json({
        code: 1,
        message: '标题和内容不能为空'
      });
    }

    // 确保author是对象格式
    const authorData = typeof author === 'string' ? JSON.parse(author) : author || {
      _id: 'anonymous',
      nickname: '匿名用户',
      avatar: ''
    };

    // 确保images是数组
    const imagesArray = Array.isArray(images) ? images :
      (typeof images === 'string' ? JSON.parse(images) : []);

    // 读取现有数据
    const travels = readTravelsData();

    // 创建新游记对象
    const newTravel = {
      id: Date.now().toString(),
      title,
      content,
      location: location || '',
      images: imagesArray,
      video: video || null,
      author: authorData,
      status: 'pending', // 新创建的游记状态为待审核
      rejectReason: null,
      isDeleted: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    // 添加到数组最前面（按时间最新排序）
    travels.unshift(newTravel);

    // 写入文件
    const success = writeTravelsData(travels);

    if (success) {
      res.status(201).json({
        code: 0,
        message: '游记创建成功，等待审核',
        data: {
          id: newTravel.id,
          images: newTravel.images,
          video: newTravel.video
        }
      });
    } else {
      throw new Error('写入游记数据失败');
    }
  } catch (error) {
    console.error('创建游记失败:', error);
    res.status(500).json({
      code: 1,
      message: '创建游记失败: ' + error.message
    });
  }
};